package top.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import top.market.model.dto.UserLoginDTO;
import top.market.model.entity.User;
import top.market.mapper.UserMapper;
import top.market.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.market.util.HashUtils;

/**
 * <p>
 * 微信小程序信息 服务实现类
 * </p>
 *
 * @author li yuhai
 * @since 2025-03-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService, UserDetailsService {

    @Override
    public User findUserByUsernameAndPassword(String username, String password) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = baseMapper.selectOne(wrapper);
        if (user == null || !HashUtils.matchBC(user.getPassword(), password)) {
            throw new UsernameNotFoundException("用户名或密码错误！");
        }
        return user;
    }

    // 这里是微信授权后进行登录的操作
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        if (userLoginDTO == null || userLoginDTO.getCode()== null){
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, "user1");
        User user = baseMapper.selectOne(wrapper);
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper =  new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        User user = baseMapper.selectOne(queryWrapper);
        return user;
    }
}
